package net.imagine.provider.fastdfs;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

public class FastDFSFileOperator implements InitializingBean {
	private String config;
	private String imageGroupName;
	
	public void setConfig(String config) {
		this.config = config;
	}
	
	public void setImageGroupName(String imageGroupName) {
		this.imageGroupName = imageGroupName;
	}
	
	public String[] uploadFile(File file) throws Exception {
		StorageClient client = StorageClientFactory.getStorageClient(imageGroupName);
		if(client == null) {
			throw new RuntimeException("Get FastDFS StorageClient Failed!");
		}
		String filePath = file.getPath();
		String ext = FilenameUtils.getExtension(filePath);
		return client.upload_file(filePath, ext, null);
	}
	
	public void downloadFile(String remoteFile, String localFile) throws Exception {
		StorageClient client = StorageClientFactory.getStorageClient(imageGroupName);
		if(client == null) {
			throw new RuntimeException("Get FastDFS StorageClient Failed!");
		}
		int result = client.download_file(imageGroupName, remoteFile, localFile);
		if(result != 0) {
			throw new RuntimeException("download file:"+ remoteFile +"from FastDFS failed");
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(config, "Config File Path Cannot Be null");
		Resource configResource = new ClassPathResource(config);
		StorageClientFactory.init(configResource);
	}
}
